﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.IO;

namespace HomeMediaBrowser
{
    /// <summary>
    /// Interaction logic for DownloadPage.xaml
    /// </summary>
    public partial class DownloadPage : PageFunction<String>
    {
        public DownloadPage()
        {
            InitializeComponent();
        }
        public virtual void UnLoaded()
        {
            SaveDownloadList();
        }
        public string GetMd5HashString(string Param)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            MainPanel MP = MW.GetMainPanel();
            return MP.GetMd5HashString(Param);
        }
        public virtual void AddNewDownloadItem(UIListItemData ItemData)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            MainPanel MP = MW.GetMainPanel();
            //check if in download list already
            int Count = DownloadLibrary.Count;
            for (int i = 0; i < Count; i++)
            {
                if (DownloadLibrary[i].Path == ItemData.Path)
                    return;
            }
            UIListItemData DownloadItem = CreateItemByDownloadXml(ItemData.Path, ItemData.Name, ItemData.Type, ItemData.DownloadPercent < 100 ? 0 : 100);
            if (ItemData.ThumbVisible == Visibility.Visible)
            {
                DownloadItem.ThumbVisible = ItemData.ThumbVisible;
                DownloadItem.ThumbDefVisible = ItemData.ThumbDefVisible;
                DownloadItem.ThumbBrush = new ImageBrush(ItemData.ThumbBrush.ImageSource);
            }
            else if (MP.CanGetThumbnail(ItemData.Type))
                MP.GetThumbnailFromServer(DownloadItem.Path);

            DownloadLibrary.Add(DownloadItem);
            if (DownloadItem.DownloadPercent < 100)
                MP.DownloadHelpers.Add(GetMd5HashString(ItemData.Path), new DownloadHelper(MP, TaskType.TASK_MEDIA, ItemData.Path));

        }
        public void RemoveDownloadItem(UIListItemData ItemData)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            MainPanel MP = MW.GetMainPanel();

            int Count = DownloadLibrary.Count;
            for (int i = 0; i < Count; i++)
            {
                if (DownloadLibrary[i].Path == ItemData.Path)
                {
                    DownloadLibrary.RemoveAt(i);
                    DownloadHelper MediaHelper = MP.DownloadHelpers[GetMd5HashString(ItemData.Path)] as DownloadHelper;
                    if (MediaHelper != null)
                        MediaHelper.Stop();
                    MP.DownloadHelpers.Remove(GetMd5HashString(ItemData.Path));
                    break;
                }
            }
            SaveDownloadList();
        }

        public void DownloadPercent(string path, int percent)
        {
            int Count = DownloadLibrary.Count;
            int i;
            Count = DownloadLibrary.Count;
            for (i = 0; i < Count; i++)
            {
                UIListItemData item = DownloadLibrary[i];
                if (item != null && item.Path == path)
                {
                    item.DownloadPercent = percent;
                }
            }
        }

        public virtual void DownloadLibraryClick(object sender, RoutedEventArgs e)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            MainPanel MP = MW.GetMainPanel();

            Button clickButton = e.OriginalSource as Button;
            UIListItemData ItemData = clickButton.DataContext as UIListItemData;

            if (clickButton == null)
                return;

            string clickButtonName = clickButton.Name;
            if (clickButtonName == "PlayButton")
            {
                RoutedEventArgs args = new RoutedEventArgs(MainPanel.PlayEvent, ItemData);
                RaiseEvent(args);
            }
            else if (clickButtonName == "CloseButton")
            {
                RemoveDownloadItem(ItemData);
            }

        }
        public int LoadDownloadList()
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            MainPanel MP = MW.GetMainPanel();

            DownloadLibrary = new MediaLibaryList();

            XmlDocument Doc = new XmlDocument();
            String AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            AppData += "\\DoCoMedia\\WinHomeServer\\ClientReceive\\DownloadList.xml";
            try
            {
                Doc.Load(AppData);

                XmlElement Root = Doc.DocumentElement;
                XmlNode Child = Root.FirstChild;
                while (Child != null)
                {
                    XmlElement Ele = Child as XmlElement;
                    string path = Ele.GetAttribute("Path");
                    string name = path;
                    int nIndex = path.LastIndexOf('\\');
                    if (nIndex >= 0)
                        name = path.Substring(nIndex + 1, path.Length - nIndex - 1);

                    ThumbType ItemType = ThumbType.THUMB_VIDEO;
                    string type = Ele.GetAttribute("Type");
                    if (type == "video")
                        ItemType = ThumbType.THUMB_VIDEO;
                    else if (type == "audio")
                        ItemType = ThumbType.THUMB_AUDIO;
                    else if (type == "image")
                        ItemType = ThumbType.THUMB_IMAGE;
                    else
                        ItemType = ThumbType.THUMB_OTHER;
                    string percent = Ele.GetAttribute("DownloadPercent");

                    UIListItemData ItemData = CreateItemByDownloadXml(path, name, ItemType, Convert.ToInt32(percent));

                    AddNewDownloadItem(ItemData);

                    if (MP.CanGetThumbnail(ItemType))
                        MP.GetThumbnailFromServer(path);

                    Child = Child.NextSibling;
                }
            }
            catch (Exception e)
            {
            }
            Binding b = new Binding();
            b.Mode = BindingMode.OneWay;
            b.Source = DownloadLibrary;

            HorizonalItems.SetBinding(ItemsControl.ItemsSourceProperty, b);
            return 0;
        }
        public int SaveDownloadList()
        {
            if (DownloadLibrary == null)
                return 0;
            XmlDocument Doc = new XmlDocument();
            String AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            AppData += "\\DoCoMedia\\WinHomeServer\\ClientReceive\\DownloadList.xml";
            XmlElement Root = Doc.CreateElement("Root");
            Doc.AppendChild(Root);


            int Count = DownloadLibrary.Count;
            int i = 0;
            for (i = 0; i < Count; i++)
            {
                UIListItemData Item = DownloadLibrary[i];
                XmlElement newElement = Doc.CreateElement("DownloadItem");
                newElement.SetAttribute("Path", Item.Path);
                switch (Item.Type)
                {
                    case ThumbType.THUMB_VIDEO:
                        newElement.SetAttribute("Type", "video");
                        break;
                    case ThumbType.THUMB_AUDIO:
                        newElement.SetAttribute("Type", "audio");
                        break;
                    case ThumbType.THUMB_IMAGE:
                        newElement.SetAttribute("Type", "image");
                        break;
                    default:
                        newElement.SetAttribute("Type", "other");
                        break;
                }
                newElement.SetAttribute("DownloadPercent", Item.DownloadPercent.ToString());
                Root.AppendChild(newElement);

            }
            Doc.Save(AppData);
            return 0;
        }
        public UIListItemData CreateItemByDownloadXml(string path, string name, ThumbType type, int percent)
        {
            MainWindow MW = App.Current.MainWindow as MainWindow;
            MainPanel MP = MW.GetMainPanel();

            UIListItemData Item = new UIListItemData();
            Item.Path = path;
            Item.Name = name;
            Item.DownloadPercent = percent;
            if (Item.DownloadPercent == 100)
            {
                Item.DownloadFinish = true;
                Item.IsDownloading = false;
            }
            else
            {
                Item.DownloadFinish = false;
                Item.IsDownloading = true;
            }
            Item.IsServer = MP.IsServer;
            Item.InitThumb(type);
            return Item;
        }
        public void RefreshMedia(string path)
        {
            int Count = DownloadLibrary.Count;
            int i;
            Count = DownloadLibrary.Count;
            for (i = 0; i < Count; i++)
            {
                UIListItemData item = DownloadLibrary[i];
                if (item != null && item.Path == path)
                {
                    item.DownloadPercent = 100;
                    item.IsDownloading = false;
                    item.DownloadFinish = true;
                }
            }
            SaveDownloadList();
        }
        public void RefreshThumb(string path, byte[] thumbdata)
        {
            int Count = DownloadLibrary.Count;
            int i = 0;
            for (i = 0; i < Count; i++)
            {
                UIListItemData item = DownloadLibrary[i];
                if (item != null && item.Path == path)
                {
                    MemoryStream Ms = new MemoryStream(thumbdata);
                    ImageSourceConverter imageSourceConverter = new ImageSourceConverter();
                    item.SetThumbVisible(Visibility.Visible);
                    item.ThumbBrush.ImageSource = (ImageSource)imageSourceConverter.ConvertFrom(Ms);
                }
            }
        }
        public MediaLibaryList DownloadLibrary;
    }
}
